package com.dries.security.common.exception;

import com.dries.security.common.api.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

/**
 * @Description: 全局异常处理
 * @Author ZSY
 * @createTime 2020/9/3 13:35
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler
    public CommonResult handler(ApiException e) {

        if (e.getErrorCode() != null) {
            return CommonResult.failed(e.getErrorCode());
        }

        return CommonResult.failed(e.getMessage());
    }

    /**
     * 统一表单验证
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult handleNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();

        return CommonResult.failed(
                Objects.requireNonNull(bindingResult.getFieldError()).getField()
                        + bindingResult.getFieldError().getDefaultMessage());
    }

}
